import axios from 'axios';
import ModalUtil from '@/utils/modal.js';
import { clearPersistor, store } from '@/redux';
import {
  ERROR,
  NO_LOGIN,
  NO_PERMISSION,
  NOT_FOUND,
  SERVICE_ERROR,
  SUCCESS,
  WARN
} from '@/constants/statusConstant.js';

const RequestUtil = axios.create({
  baseURL: '/api',
  timeout: 10 * 1000,
  timeoutErrorMessage: '请求超时，请稍后重试',
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
});

RequestUtil.interceptors.request.use(
  (config) => {
    const userStore = store.getState().user;
    config.headers.Authorization = `Bearer ${userStore?.token}`;
    return config;
  },
  (error) => {
    console.log('请求出错', error);
    return Promise.reject(error);
  }
);

RequestUtil.interceptors.response.use(
  (response) => {
    const data = response.data;
    const code = data.code;
    const msg = data.msg;
    if (data && code !== SUCCESS) {
      switch (code) {
        case WARN:
          ModalUtil.msgWarning(msg);
          break;
        case NO_LOGIN:
          ModalUtil.msgError(
            '未登录 或 登录已过期，请重新登录',
            () => {
              clearPersistor();
              if (window.location.pathname !== '/login') {
                window.location.href = '/login';
              }
            },
            'loginError'
          );
          return Promise.reject('无效的会话，或者会话已过期，请重新登录。');
        case NO_PERMISSION:
          ModalUtil.msgWarning(msg);
          break;
        case NOT_FOUND:
          ModalUtil.msgError(msg);
          break;
        case SERVICE_ERROR:
          ModalUtil.msgError(msg);
          break;
        case ERROR:
          ModalUtil.msgError(msg);
          break;
        default:
          ModalUtil.msgError('系统未知错误，请反馈给管理员');
          return Promise.reject('error');
      }
    }
    return data;
  },
  (error) => {
    console.log('响应出错：', error);
    let { message } = error;
    if (message === 'Network Error') {
      message = '后端接口连接异常';
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时';
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口 ' + message.slice(-3) + ' 异常';
    }
    ModalUtil.msgError(message);
    return Promise.reject(error);
  }
);

export default RequestUtil;
